<template>
  <div class="imageSelectedArea">
    <el-card class="box-card" style="min-height: 600px;">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form label-position="right" ref="form" :rules="rules" size="mini"  label-width="80px" :model="queryParams">
            <el-row>
              <el-col :span="12">
                <el-form-item label="场景名称" prop="scenariosType">
                  <el-select v-model="queryParams.scenariosType" placeholder="请选择场景" disabled>
                    <el-option v-for="dict in dict.type.task_scenarios_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务类型" prop="taskType">
                  <el-select v-model="queryParams.taskType" :disabled="!!queryParams.id" placeholder="请选择任务类型" @change="changeTaskType">
                    <el-option v-for="dict in taskTypeList" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row v-if="queryParams.taskType === '2'"> -->
              <!-- 分行任务时，必须选择录像机IP和通道 -->
              <!-- <el-col :span="12">
                <el-form-item label="录像机" prop="equipmentId" v-if="queryParams.taskType === '2'">
                  <el-input v-model="queryParams.equipmentId" placeholder="请选择录像机" suffix-icon="el-icon-caret-right"
                    :readonly="true" @click.native="getEquipmentInfo" :disabled="!!queryParams.id" />
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="IP" prop="equipmentIp" v-if="queryParams.taskType === '2'">
                  <el-input v-model="queryParams.equipmentIp" placeholder="录像机IP" :disabled="true" />
                </el-form-item>
              </el-col> -->
            <!-- </el-row> -->
            <!-- <el-row>
              <el-col :span="12">
                <el-form-item label="通道号" prop="equipmentChannel" v-if="queryParams.taskType === '2'">
                  <el-select v-model="queryParams.equipmentChannel" :disabled="!!queryParams.id" placeholder="请选择通道">
                    <el-option v-for="dict in channelKeyList" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-form-item label="支行" prop="orgCode">
              <treeselect v-model="queryParams.orgCode"
                @input="changeOrgCode"
                :disable-branch-nodes="true"
                :disabled="!!queryParams.id"
                 search-nested
                :options="deptOptions"
                :normalizer="normalizer"
                 placeholder="请选择支行"
                style="width:100%"/>
            </el-form-item>
            <el-form-item label="摄像通道" prop="cameraIdFH" v-if="queryParams.taskType === '2'">
              <el-select v-model="queryParams.cameraIdFH" clearable :disabled="!!queryParams.id" placeholder="请选择通道">
                <el-option v-for="dict in channelKeyList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-row>
              <el-col :span="12">
                <el-form-item :label="queryParams.taskType === '2' ? '通道预览': '摄像通道'" prop="cameraId">
                  <el-select v-model="queryParams.cameraId" :disabled="!!queryParams.id"  clearable placeholder="请选择摄像头" style="width:100%" @change="cameraChange" filterable>
                    <el-option
                      v-for="item in videoOptions"
                      :key="item.cameraId"
                      :label="item.cameraName"
                      :value="item.cameraId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="ID">
                  <el-input v-model="cameraIdText " :disabled="!!queryParams.id" v-clipboard:copy="queryParams.cameraId" v-clipboard:success="clipboardSuccess"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="框选类型" prop="equipmentType">
                  <el-select v-model="rectangleType" placeholder="框选类型" style="width:100%" @change="rectangleTypeChange">
                    <el-option
                      v-for="dict in rectangleTypeList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="原始坐标">
                  <el-input v-model="coordinates"/>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24" v-show="rectangleType === '1'">
                <el-form-item label="缩放坐标">
                  <el-input v-model="coordinatesImg"/>
                </el-form-item>
              </el-col> -->
              <el-col :span="24">
                <el-form-item label="顶点坐标">
                  <el-input v-model="changeCoordinates" v-clipboard:copy="changeCoordinates" v-clipboard:success="clipboardSuccess"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="通用参数">
                  <el-input v-model="queryParams.commonConfig"  maxlength="6000" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-button type="primary" @click="selectLocalImage">获取图片</el-button>
          <el-button type="primary" style="margin-left: 5px;" @click="clearPoints">清除</el-button>
          <el-button type="primary" @click="saveCoordinates">添加坐标</el-button>
          <el-button type="success" @click="saveSceneCameras">保存摄像头</el-button>
          <!-- <input type="file" id="fileInput" ref="fileInput" accept="image/*" style="display: none;" @change="handleFileInputChange" /> -->
          <el-row style="margin-top: 5px;">
            <el-table ref="singleTable" size="mini" max-height="200px"  :data="queryParams.areaListData" highlight-current-row @current-change="handleAreaCurrentChange" style="width: 100%">
              <el-table-column prop="areaName" label="区域名称" width="80px" ></el-table-column>
              <el-table-column prop="boxes" label="区域坐标" ></el-table-column>
              <el-table-column label="操作" width="60px" >
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="deleteRow(scope.$index, queryParams.areaListData)"
                    type="text"
                    size="small">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-col>
        <el-col :span="16">
          <div v-show="rectangleType === '1' && !!imageUrl" ref="imageContainer" class="imageContainer">
            <img ref="displayImage" @load="imageLoad" alt="图片预览" :src="imageUrl" style="width: 100%; height: 100%; max-width: 100%;"/>
            <div class="selectedArea" ref="selectedArea"></div>
          </div>
          <div v-show="rectangleType === '2' && !!imageUrl" id="irregularContainer" class="imageContainer">
            <img ref="irregularDisplayImage" @load="imageLoad" alt="图片预览" id="image" :src="imageUrl" style="width: 100%; height: 100%; max-width: 100%;"/>
            <canvas id="canvas" ref="canvas"></canvas>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog :visible.sync="showDialog" width="1280px" title="请选择录像机" append-to-body>
      <el-form :model="equipMentParamslistDataQuery" ref="showDialogQueryQueryForm" size="small" :inline="true"
        abel-width="88px">
        <el-form-item label="机构名称" prop="bankName">
          <el-input v-model="equipMentParamslistDataQuery.bankName" placeholder="请输入分/支行名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getEquipmentInfo">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetEquipMentParamslistDataQuery()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="equipMentListData" @row-click="handleSelect" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column prop="equipmentId" label="录像机编号" />
        <el-table-column prop="bankCode" label="网点号" />
        <el-table-column prop="bankName" label="网点名称" />
        <el-table-column prop="subBankCode" label="分行号" />
        <el-table-column prop="subBankName" label="分行名称" />
        <el-table-column prop="equipmentIp" label="设备IP" />
        <el-table-column prop="equipmentPort" label="设备端口" />
      </el-table>
      <pagination v-show="equipMentListDataTotal > 0" :total="equipMentListDataTotal" :page.sync="equipMentParamslistDataQuery.pageNum"
        :limit.sync="equipMentParamslistDataQuery.pageSize" @pagination="queryEquipmentInfoList" />
    </el-dialog>
  </div>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { cameraInfoList, queryCameraPicture } from "@/api/modelTest/imageSelectedArea";
import { listCamera, getCamera, delCamera, addCamera, updateCamera } from "@/api/iis/sceneCameraList";
import { listConfig as channelList } from "@/api/iis/equipment";
// import { listConfig as channelList } from "@/api/iis/channel";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "imageSelectedArea",
  components: { Treeselect },
  dicts: ['sys_normal_disable','task_frequency_type',"task_scenarios_type"],
  data() {
    return {
      deptOptions: [],
      orgTypeOptions: [],
      queryParams: {
        scenariosType: "",
        taskType: "2",
        equipmentIp: "",
        equipmentId: null,
        equipmentChannel: null,
        cameraIdFH: null,
        cameraId: null,
        orgCode: null,
        areaListData: [],
        commonConfig: "",
        id: null
      },
      coordinates: "",
      coordinatesImg: "",
      imgNatural: "",
      imageUrl: "",
      areaName: "",

      videoOptions: [],
      deptList: [],
      rules: {
        scenariosType: [
          { required: true, message: "请选择场景", trigger: "blur" }
        ],
        cameraId: [
          { required: false, message: "请选择总行摄像头", trigger: "blur" }
        ],
        // equipmentId: [
        //   { required: true, message: "请选择录像机", trigger: "blur" }
        // ],
        cameraIdFH: [
          { required: true, message: "请选择摄像头", trigger: "blur" }
        ]
      },
      rectangleType: "",
      rectangleTypeList: [
        {
          value: "1",
          label: "标准矩形框"
        },
        {
          value: "2",
          label: "多边形框"
        }
      ],
      points: [],
      taskTypeList: [
        {
          value: "1",
          label: "总行任务"
        },
        {
          value: "2",
          label: "分行任务"
        },
        {
          value: "3",
          label: "浩云分行"
        }
      ],
      loading: false,
      equipMentListData: [],
      equipMentListDataTotal: 0,
      showDialog: false,
      equipMentParamslistDataQuery: {
        pageNum: 1,
        pageSize: 10,
        bankName: ""
      },
      channelKeyList: [],
      currentRow: null
    };
  },
  watch: {
    // 'queryParams.equipmentId': {
    //   handler(val, oldVal) {
    //     console.log('equipmentId changed to:', val);
    //     if (val) {
    //       this.getChannelKeyList();
    //     }
    //     // 处理逻辑
    //   },
    //   immediate: true // 如果初始值已经存在，则会立即触发一次
    // },
    "queryParams.taskType": {
      handler(val) {
        if (this.queryParams.id === null) {
          this.queryParams.equipmentIp = "";
          this.queryParams.equipmentId = null;
          this.queryParams.equipmentChannel = null;
          this.queryParams.cameraId = null;
          this.queryParams.orgCode = null;
          this.queryParams.bankCode = "";
          this.queryParams.areaListData = [];
          this.queryParams.commonConfig = "";
          this.coordinates = ""
        }
      },
      immediate: true
    },
    "queryParams.cameraId": {
      handler(val, oldVal) {
        this.cameraIdText = val;
      },
      immediate: true // 如果初始值已经存在，则会立即触发一次
    },
    coordinates: {
      handler(val) {
        if (this.rectangleType === "1" && val) {
          try {
            let coordinates = JSON.parse(val)
            let changeCoordinates = []
            changeCoordinates.push([coordinates.x, coordinates.y])
            changeCoordinates.push([`${parseInt(coordinates.x) + parseInt(coordinates.width)}`, `${parseInt(coordinates.y) + parseInt(coordinates.height)}`])
            this.changeCoordinates = JSON.stringify(changeCoordinates)

          } catch (e) {
            console.log(e)
          }

        } else {
          this.changeCoordinates = val
        }
      },
      immediate: true
    }
  },
  created() {
    const scenariosType = this.$route.query && this.$route.query.scenariosType;
    const sceneCameraId = this.$route.query && this.$route.query.sceneCameraId;
    console.log("$route.query", this.$route.query)
    this.queryParams.scenariosType = scenariosType;
    this.queryParams.id = sceneCameraId || null
    listDept().then(response => {
      this.deptList = response.data
      this.deptOptions = this.handleTree(response.data, "deptId");
      if (sceneCameraId) {
        getCamera(sceneCameraId).then(response => {
          this.queryParams = response.data;
          try {
            this.queryParams.areaListData = JSON.parse(this.queryParams.boxes)
          } catch (error) {
            this.queryParams.areaListData = []
          }
          this.cameraIdText = this.queryParams.cameraId
          const dept = this.deptList.find(item => item.deptCode === this.queryParams.bankCode)
          if (dept && dept.deptId) {
            this.queryParams.orgCode = dept.deptId;
            this.changeOrgCode()
          }
          if (!this.queryParams.areaListData || this.queryParams.areaListData.length == 0) {
            // 切换成标准矩形框
            this.rectangleType = "1"
            this.setupImageSelection()
          }
        });
      } else {
        // 切换成标准矩形框
        this.rectangleType = "1"
        this.setupImageSelection()
      }
    });
  },
  mounted() {
    window.addEventListener("resize", () => {
      // this.initCanvas()
      // this.clearPoints()
      // this.setupCanvas()
    });
    this.setupImageSelection();
  },
  methods: {
    saveSceneCameras() {
      let queryParams = Object.assign({}, this.queryParams);
      let scenariosType = queryParams.scenariosType;
      if (!scenariosType) {
        this.$message({
          message: "请选择场景类型",
          type: "error"
        });
        return false
      }
      if (!queryParams.bankCode) {
        const dept = this.deptList.find(item => item.deptId === queryParams.orgCode)
        if (dept && dept.deptCode) {
          queryParams.bankCode = dept.deptCode;
        }
      }
      if ( queryParams.taskType === "2" && queryParams.cameraIdFH) {
        this.channelKeyList.forEach(camera => {
          if (camera.value === queryParams.cameraIdFH) {
            queryParams.equipmentIp = camera.item.equipmentIp
            queryParams.equipmentId = camera.item.equipmentId
            queryParams.equipmentChannel = camera.item.equipmentChannel
          }
        });
        if (!queryParams.equipmentIp || !queryParams.equipmentId || !queryParams.equipmentChannel) {
          this.$message({
            message: "请选择正确的摄像头",
            type: "error"
          });
          return false
        }
      }
      if (!queryParams.areaListData || queryParams.areaListData.length == 0) {
        queryParams.boxes = ""
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$confirm('未标注坐标，确定新增吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (queryParams.id) {
                updateCamera(queryParams).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.$router.push('/iis/sceneParamsCameras/index/' + scenariosType)
                });
              } else {
                addCamera(queryParams).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.$router.push('/iis/sceneParamsCameras/index/' + scenariosType)
                });
              }
            }).catch(() => {})
          }
        });
      } else {
        queryParams.boxes = JSON.stringify(queryParams.areaListData);
        if (queryParams.id) {
          updateCamera(queryParams).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$router.push('/iis/sceneParamsCameras/index/' + scenariosType)
          });
        } else {
          addCamera(queryParams).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$router.push('/iis/sceneParamsCameras/index/' + scenariosType)
          });
        }
      }
    },
    saveCoordinates() {
      if (!this.changeCoordinates) {
        this.$message.error("请选择区域坐标");
        return;
      }
      let self = this;
      this.$prompt('请输入区域名称!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        if (!value) {
          this.$message.error("请输入区域名称");
          return false
        }
        this.queryParams.areaListData.push({
          areaName: value,
          boxes: self.changeCoordinates,
          rectangleType: self.rectangleType
        });
        self.clearPoints()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    handleAreaCurrentChange(val) {
      this.currentRow = val;
      this.rectangleType = this.currentRow && this.currentRow.rectangleType || "1"
      this.rectangleTypeChange()

      this.$nextTick(() => {
        // this.currentRow.boxes 这个存储的时顶点坐标，如果是标准矩形框，需要转换成（左上角+宽高模式）[[x1,y1], [x2,y2]]
        if (this.rectangleType === "1") {
          const boxes = JSON.parse(this.currentRow.boxes)
          const coordinates = {
            x: boxes[0][0],
            y: boxes[0][1],
            width: boxes[1][0] - boxes[0][0],
            height: boxes[1][1] - boxes[0][1]
          }
          this.coordinates = JSON.stringify(coordinates)
          // 在反显划线前，需要把坐标按照当前画面大小进行缩放
          const coordinatesImg = this.transferRelativeCoordinates(coordinates.x, coordinates.y, coordinates.width, coordinates.height)
          this.coordinatesImg = JSON.stringify(coordinatesImg)
          this.drawRectangleByData(coordinatesImg.x, coordinatesImg.y, coordinatesImg.width, coordinatesImg.height)
        } else if (this.rectangleType === "2") {
          const boxes = JSON.parse(this.currentRow.boxes)
          this.points = this.transferRelativeCoordinatesIrregular(boxes)
          this.coordinates = JSON.stringify(boxes)
          this.drawPolygon();
        }
      })

      // this.coordinates = this.currentRow.boxes
    },
    getChannelKeyList(deptCode) {
      const queryParams = {
        pageNum: 1,
        pageSize: 1000,
        status: "0",
        bankCode: deptCode
      }
      self = this
      self.channelKeyList = []
      channelList(queryParams).then(response => {
        const rows = response.rows;
        self.channelKeyList = rows.map((item) => {
          return {
            value: item.channelId + "",
            label: item.remark,
            item: item
          }
        })
        if (!self.queryParams.cameraIdFH && self.queryParams.equipmentId && self.queryParams.equipmentChannel) {
          this.channelKeyList.forEach(camera => {
            if (camera.item && camera.item.equipmentId === self.queryParams.equipmentId && camera.item.equipmentChannel === self.queryParams.equipmentChannel) {
              self.queryParams.cameraIdFH = camera.item.channelId + "";
              return false
            }
          });
        }
      });
    },
    handleCurrentChange(currentRow) {
      this.selectedRow = currentRow;
    },
    handleSelect(row) {
      this.$refs.form.clearValidate(['equipmentId']);
      this.queryParams.equipmentId = row.equipmentId;
      this.queryParams.equipmentIp = row.equipmentIp;
      this.queryParams.bankCode = row.bankCode;

      const dept = this.deptList.find(item => item.deptCode === this.queryParams.bankCode)
      if (!dept || !dept.deptId) {
        return false
      }
      this.queryParams.orgCode = dept.deptId;
      this.showDialog = false;
    },
    resetEquipMentParamslistDataQuery() {
      this.equipMentParamslistDataQuery = {
        pageNum: 1,
        pageSize: 10,
        bankName: ""
      }
      this.getEquipmentInfo()
    },
    getEquipmentInfo() {
      this.loading = true;
      this.queryEquipmentInfoList()
      this.showDialog = true;
    },
    queryEquipmentInfoList() {
      equipmentListConfig(this.equipMentParamslistDataQuery).then(response => {
        this.equipMentListData = response.rows;
        this.equipMentListDataTotal = response.total;
        this.loading = false;
      });
    },
    changeTaskType(taskType) {
      if (taskType === '1' || taskType === '3') {
        // 总行任务 - cameraId is required
        this.rules.cameraId[0].required = true;
      } else if (taskType === '2') {
        // 分行任务 - equipmentId and channelKey are required
        this.rules.cameraId[0].required = false;
      }
      // Clear validation for the form
      this.$refs.form.clearValidate();
    },
    imageLoad() {
      console.log("imageLoad");
      this.rectangleTypeChange();
      this.getImgNatural()
    },
    cameraChange(){
      this.imageUrl = ""
      this.imgNatural = ""
      this.clearPoints();
      this.selectLocalImage()
    },
    removeAllEventListener() {
      const container = this.$refs.imageContainer;
      container.removeEventListener("mousedown", () =>{});
      container.removeEventListener("mousemove", () =>{});
      container.removeEventListener("mouseup", () =>{});

      const canvas = this.$refs.canvas;
      canvas.removeEventListener("click", () =>{});
    },

    rectangleTypeChange() {
      // 移除所有事件监听器
      this.removeAllEventListener();
      // 移除所有点位信息
      this.clearPoints()
      // 改变框选图类型
      if (this.rectangleType === '1') {
        // 切换成标准矩形框
        this.setupImageSelection()
      } else if (this.rectangleType === '2') {
        // 切换成自选不规则框
        this.setupImageSelectionIrregular()
      }
    },
    drawRectangleByData(x, y, width, height) {
      const selectedArea = self.$refs.selectedArea;
      selectedArea.style.left = x + "px";
      selectedArea.style.top = y + "px";
      selectedArea.style.width = width + "px";
      selectedArea.style.height = height + "px";
      selectedArea.style.display = "block";
    },
    changeOrgCode(deptId) {
      const dept = this.deptList.find(item => item.deptId === deptId)
      if (!dept || !dept.deptCode) {
        return false
      }
      if (this.queryParams.taskType === '2') {

        this.getChannelKeyList(dept.deptCode)
      }
      // 改变部门时，清空摄像头列表
      this.videoOptions = []
      this.cameraChange()
      let queryParams = {
        deptCode: dept.deptCode,
        status: "0"
      };
      const self = this;
      cameraInfoList(queryParams).then(response => {
        self.videoOptions = response.rows;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    clearPoints() {
      this.points = [];
      this.coordinates = ""
      // 清除canvas画布
      this.initCanvas()
      // 清除矩形框已框选的图型
      this.clearCoordinates()
    },
    /** 复制成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    clearCoordinates(){
      const selectedArea = this.$refs.selectedArea;
      selectedArea.style.left = "0px";
      selectedArea.style.top = "0px";
      selectedArea.style.width = "0px";
      selectedArea.style.height = "0px";
      selectedArea.style.display = "none";
    },
    selectLocalImage(){
      // this.$refs.fileInput.click()
      if(!this.queryParams.cameraId){
        this.$message.error("请选择摄像头")
        return false
      }
      let queryParams = {
        cameraId: this.queryParams.cameraId
      }
      queryCameraPicture(queryParams).then(response => {
        this.imageUrl = response.data
      })
    },
    setupImageSelection() {
      const img = this.$refs.displayImage;
      const container = this.$refs.imageContainer;
      let isDrawing = false;
      let startX, startY;
      self = this;

      container.addEventListener("mousedown", (e) => {
        const selectedArea = self.$refs.selectedArea;
        isDrawing = true;
        self.coordinates = ""
        startX = e.offsetX;
        startY = e.offsetY;
        selectedArea.style.left = startX + "px";
        selectedArea.style.top = startY + "px";
        selectedArea.style.width = "0px";
        selectedArea.style.height = "0px";
        selectedArea.style.display = "block";
      });

      container.addEventListener("mousemove", (e) => {
        const selectedArea = self.$refs.selectedArea;

        if (isDrawing) {
          const x = Math.max(0, Math.min(e.offsetX, startX));
          const y = Math.max(0, Math.min(e.offsetY, startY));
          const width = Math.min(Math.abs(e.offsetX - startX), img.width - x);
          const height = Math.min(Math.abs(e.offsetY - startY), img.height - y);
          selectedArea.style.left = x + "px";
          selectedArea.style.top = y + "px";
          selectedArea.style.width = width + "px";
          selectedArea.style.height = height + "px";
          selectedArea.style.display = "block";
          self.updateCoordinates(x, y, width, height);
        }
      });
      container.addEventListener("mouseup", () => {
        isDrawing = false;
      });
    },
    getImgNatural() {
      let img = ""
      if (this.rectangleType === '1') {
        img = this.$refs.displayImage;
      } else if (this.rectangleType === '2') {
        img = this.$refs.irregularDisplayImage;
      }
      const imgNaturalWidth = img.naturalWidth || 0;
      const imgNaturalHeight = img.naturalHeight || 0;
      this.imgNatural = `${imgNaturalWidth.toString()} * ${imgNaturalHeight.toString()}`
    },
    setupImageSelectionIrregular() {
      // 不规则图形
      const canvas = this.$refs.canvas;
      this.setupCanvas()
      canvas.addEventListener("click", this.addPoint);
    },
    setupCanvas(){
      const irregularDisplayImage = this.$refs.irregularDisplayImage;
      const canvas = this.$refs.canvas;
      canvas.width = (irregularDisplayImage.width-1).toFixed(0);
      canvas.height = (irregularDisplayImage.height-1).toFixed(0);
    },
    addPoint(e) {
      const { offsetX, offsetY } = this.getMousePosition(e);
      this.points.push({ x: offsetX, y: offsetY });
      const pointsIrregular = this.transferNaturalCoordinatesIrregular(this.points)
      console.log("addPoint", offsetX, offsetY, this.points, pointsIrregular);
      // 需要转换成原始图片尺寸对应的坐标后展示
      this.coordinates = JSON.stringify(pointsIrregular);
      this.drawPolygon();
    },
    drawPolygon() {
      const context = this.initCanvas()
      context.beginPath();
      context.moveTo(this.points[0].x, this.points[0].y);
      for (let i = 1; i < this.points.length; i++) {
        context.lineTo(this.points[i].x, this.points[i].y);
      }
      if (this.points.length > 1) {
        context.closePath();
      }
      context.strokeStyle = "#FF0000"
      context.stroke();
    },
    initCanvas() {
      const context = canvas.getContext("2d");
      context.clearRect(0, 0, canvas.width, canvas.height);
      return context;
    },
    getMousePosition(e) {
      const canvas = this.$refs.canvas;
      const rect = canvas.getBoundingClientRect();
      const mouseX = Math.max(0, e.clientX - rect.left);
      const mouseY = Math.max(0, e.clientY - rect.top);
      return {
        offsetX: mouseX,
        offsetY: mouseY
      };
    },
    updateCoordinates(x, y, width, height){
      const naturalCoordinates = this.transferNaturalCoordinates(x, y, width, height)
      this.coordinates =  JSON.stringify(naturalCoordinates)
    },
    // 转换为自然坐标,按照原始图片大小和界面显示的大小缩放比进行转换
    // x,y,width,height为相对坐标
    // 转换矩形图形坐标:返回的结果为绝对坐标，系统存储的坐标
    transferNaturalCoordinates(x, y, width, height){
      const img = this.$refs.displayImage;
      const imgNaturalWidth = img.naturalWidth;
      const imgWidth = img.width;
      const scalingRatio = imgWidth / imgNaturalWidth;
      return {
        x: (x / scalingRatio).toFixed(0),
        y: (y / scalingRatio).toFixed(0),
        width: (width / scalingRatio).toFixed(0),
        height: (height / scalingRatio).toFixed(0)
      }
    },
    // 转换不规则图形坐标:返回的结果为绝对坐标，系统存储的坐标
    transferNaturalCoordinatesIrregular(points){
      const irregularDisplayImage = this.$refs.irregularDisplayImage;
      const imgNaturalWidth = irregularDisplayImage.naturalWidth;
      const imgWidth = irregularDisplayImage.width;
      const scalingRatio = imgWidth / imgNaturalWidth;
      const pointsIrregular = points.map(item => {
        const { x, y } = item;
        return [
          (x / scalingRatio).toFixed(0),
          (y / scalingRatio).toFixed(0)
        ]
      });
      return pointsIrregular
    },
    transferRelativeCoordinatesIrregular(points) {
      const irregularDisplayImage = this.$refs.irregularDisplayImage;
      const imgNaturalWidth = irregularDisplayImage.naturalWidth;
      const imgWidth = irregularDisplayImage.width;
      const scalingRatio = imgWidth / imgNaturalWidth;
      const pointsIrregularRelative = points.map(item => {
        return {
          x: (item[0] * scalingRatio).toFixed(0),
          y: (item[1] * scalingRatio).toFixed(0)
        }
      });
      return pointsIrregularRelative
    },
    // 获取相对坐标：转换为自然坐标,按照原始图片大小和界面显示的大小缩放比进行转换
    // x,y,width,height为绝对坐标（基准是源图片尺寸与左上角为原点）
    // 返回相对坐标，在当前界面图片中显示的坐标
    transferRelativeCoordinates(x, y, width, height) {
      const img = this.$refs.displayImage;
      const imgNaturalWidth = img.naturalWidth;
      const imgWidth = img.width;
      const scalingRatio = imgWidth / imgNaturalWidth;
      return {
        x: (x * scalingRatio).toFixed(0),
        y: (y * scalingRatio).toFixed(0),
        width: (width * scalingRatio).toFixed(0),
        height: (height * scalingRatio).toFixed(0),
      }
    }
  }
};
</script>

<style scoped lang="scss">
.imageContainer {
  position: relative;
  display: inline-block;
}
.selectedArea {
  position: absolute;
  border: 2px solid red;
  display: none;
}

#image {
  display: block;
}
#canvas {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
